const vscode = require('vscode');
const util = require('./util');

module.exports = function (context) {
  // 注册HelloWord命令
  context.subscriptions.push(vscode.commands.registerTextEditorCommand('extension.alignDefine', (editor) => {
    alignDefines(editor);
  }));
};

function alignDefines(editor) {
  if (editor) {
    editor.selections.forEach((sel) => {
      let variable_1_max = 0;
      let variable_2_max = 0;
      let variable_3_max = 0;
      let array = [];
      let index = [];
      for (let i = sel.start.line; i <= sel.end.line; i++) {
        let textline = editor.document.lineAt(i);
        let x = textline.b.trim();
        x = x.match("^\\s*#\\s*define\\s+(\\S+)\\s*(((?!/\\*|//).)*)(.*)");
        if (x) {
          let p = [];
          p.push(x[0].trim());
          p.push(x[1].trim());
          p.push(x[2].trim());
          p.push(x[4].trim());
          array.push(p);
          index.push(i);
          if (p[1]) {
            if (p[1].length > variable_1_max) {
              variable_1_max = p[1].length;
            }
          }
          if (p[2]) {
            if (p[2].length > variable_2_max) {
              variable_2_max = p[2].length;
            }
          }
          if (p[4]) {
            if (p[4].length > variable_3_max) {
              variable_3_max = p[4].length;
            }
          }
        }
      }
      let variable_1_index = 9 + variable_1_max; // 定义值的位置
      let variable_2_index = variable_1_index + variable_2_max + 1;//注释的位置
      editor.edit((editBuilder) => {
        for (let i = 0; i < array.length; ++i) {

          var location = new vscode.Range(index[i],
            0,
            index[i],
            editor.document.lineAt(index[i]).b.length);
          var str = "#define " + array[i][1];
          if (array[i][2]) {
            var len = str.length;
            for (let j = 0; j < variable_1_index - len; j++) {
              str = str + ' ';
            }
            str = str + array[i][2];
          }
          if (array[i][3]) {
            var len = str.length;
            for (let j = 0; j < variable_2_index - len; j++) {
              str = str + ' ';
            }
            str = str + array[i][3];
          }
          editBuilder.replace(location, str);
        }
      });
    });
  }

}